<template>
    <div class="location">
        <div id="container"></div>
    </div>
</template>

<script>
import bMap from "@/utils/bMap.js";
import gps from "@/utils/gps.js";
    export default {
        name:'location',
        props:['plate_no'],
        data(){
            return {
                map:{},
                ALicense:'', //车牌
                ASpeed:'', //车速
                AState:'', //状态
                ALocationName:'', //地址
                AAngle:'0', //角度
                ALocationTime:'',//时间
                pic:require('@/assets/images/truck.png'),
                infoready:false,//信息窗体数据是否加载完毕
                timer:null
            }
        },
        created() {
            
        },
        methods:{
            getLocation:function(refresh){
                var _this=this;
                var loading;
				if(!refresh)
				{
					loading = this.$toast.loading({
					  duration:60000,
					  message: '位置信息加载中...',
					  forbidClick: true,
					  loadingType: 'spinner'
					});
				}
                this.axios.get('home/getLocation',{plate_no: this.plate_no}).then((res)=>{
                    loading&&loading.clear();
                    if(res.errno==0)
                    {
                        var data = res.data[0];
                        if(!data.plate_no)
                        {
                            _this.$toast('抱歉,该车辆为我司外调车辆,暂无GPS数据!!! \n如您有任何问题,敬请致电我司操作电话: 0755 - 2664 6158');
                        }
                        _this.ALicense = data.plate_no;
                        _this.ASpeed = parseInt(data.speed)/10;
                        _this.AState = data.state;
                        _this.ALocationTime = data.location_time; 
                        _this.AAngle = data.Angle;
                        var lng=data.longitude,lat=data.latitude;
                        if(!lng){
                            _this.$toast("【经纬度不完整!】" + "\n" + "经度：" + lng + "\n" + "纬度：" + lat)
                            return;
                        }
                        if(!lat){
                            _this.$toast("【经纬度不完整!】" + "\n" + "经度：" + lng + "\n" + "纬度：" + lat)
                            return;
                        }
                        //数据库存的坐标是WGS-84 需要先将它转为GCJ-02 再转为BD-09
                        var loc = gps.gcj_encrypt(lat,lng);
                        loc = gps.bd_encrypt(loc.lat,loc.lon);
                        var point = new BMap.Point(loc.lon, loc.lat);
                        _this.addMarker(point);
                        var gc = new BMap.Geocoder();  //初始化，Geocoder类
                        gc.getLocation(point, function (rs) {   //getLocation函数用来解析地址信息，分别返回省市区街等
                            var addComp = rs.addressComponents,
                                province = addComp.province,//获取省份
                                city = addComp.city,//获取城市
                                district = addComp.district,//区
                                street = addComp.street,//街
                                streetNumber = addComp.streetNumber ? addComp.streetNumber + "号" : "";
                            var location_name = province + city + district + street + streetNumber;
                            _this.ALocationName = location_name;
                            _this.infoready=true;
                            var infoWindow = _this.addInfoWindow();
                            _this.map.openInfoWindow(infoWindow, point);
                        });
                    }else{
                        _this.$toast('抱歉,该车辆为我司外调车辆,暂无GPS数据!!! \n如您有任何问题,敬请致电我司操作电话: 0755 - 2664 6158');
                    }
                }).catch((err)=>{
                    _this.$toast('抱歉,该车辆为我司外调车辆,暂无GPS数据!!! \n如您有任何问题,敬请致电我司操作电话: 0755 - 2664 6158');
                    loading&&loading.clear();
                })
            },
            
            addMarker:function(point){
                var _this=this;
                _this.map.clearOverlays();
                var myIcon = new BMap.Icon(this.pic, new BMap.Size(14,32), {    
                    // 指定定位位置。   
                    // 当标注显示在地图上时，其所指向的地理位置距离图标左上    
                    // 角各偏移30像素和30像素。您可以看到在本例中该位置即是   卡车正中心   
                    imageSize:new BMap.Size(14, 32),    
                });      
                // 创建标注对象并添加到地图   
                var marker = new BMap.Marker(point, {icon: myIcon,rotation:this.AAngle});
                marker.addEventListener("click", function(){
                    _this.openInfoWindow(point);
                });
                this.map.addOverlay(marker);
                this.map.panTo(point);
                  
            },
            openInfoWindow:function(point){
                if(this.infoready)
                {
                    // 创建信息窗口对象
                    var infoWindow = this.addInfoWindow();
                    this.map.openInfoWindow(infoWindow, point); //开启信息窗口
                }else{
                    this.$toast('数据加载中,请稍等');
                }
            },
            addInfoWindow:function(){
                var opts = {
                    width : 180,     // 信息窗口宽度
                    height: 0,     // 信息窗口高度
                    title : "【当前车辆信息】" , // 信息窗口标题
                    message: "信息加载中······",
                    enableCloseOnClick:false,
                };
                var infoWindow = new BMap.InfoWindow("车牌：" + this.ALicense + "<br>" + "速度：" + this.ASpeed +"km/h" + "<br>" + "状态：" + this.AState + "<br>" + "地址：" + this.ALocationName + "<br>" + "时间：" + this.ALocationTime,opts);
                return infoWindow;
            },
        },
        beforeDestroy() {
            if(this.timer) {
                clearInterval(this.timer);
            }
        },
        mounted:function(){
            var _this=this;
            this.$nextTick(function(){
                bMap('5kxWDcyxeBL8AfZlQET7GrBgPEmUPf8a').then(()=>{
                    _this.map=new BMap.Map("container");
                    var point = new BMap.Point(116.404,39.915);//初始默认北京天安门
                    _this.map.centerAndZoom(point, 16);
                    _this.map.addControl(new BMap.NavigationControl());
                    _this.map.enablePinchToZoom(true);
                    _this.getLocation();
                    /**
                     * 定时任务 每10s刷新一次数据
                     */
                    if(_this.timer) {
                        clearInterval(_this.timer);
                    }
                    _this.timer = setInterval(function(){
                        _this.getLocation(true);
                    },10000)
                }).catch(err=>{
                    _this.$toast('地图初始化失败,请刷新重试');
                })
            })
        }
    }
</script>

<style lang="less" scoped>
    #container{
        width: 100%;
        height: calc(100vh - 90px);
    }
</style>
<style>
    .location .BMap_bubble_title{
        font-size: .36rem;
    }
    .location .BMap_bubble_content{
        font-size: .34rem;
    }
</style>
